package com.apesay.controller;

import com.alibaba.fastjson.JSONObject;
import com.apesay.exception.ServiceException;
import com.apesay.security.CustomAuthenticationException;
import com.apesay.service.auth.AccountService;
import com.apesay.service.auth.PermissionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/check")
public class CheckController {
	Logger logger = LoggerFactory.getLogger(CheckController.class);
	@Resource
	private PermissionService permissionService;
	@Resource
	AccountService accountService;
	@RequestMapping("/register")
	@ResponseBody
	public String save(String realname,String username, String email, String password, HttpSession session) {
		String msg = "success";
		try {
			JSONObject accountObject = accountService.findByName(username);
			if (accountObject!=null) {
				msg = "用户名已存在";
			}else {
				accountObject = accountService.findByName(email);
				if (accountObject!=null) {
					msg = "注册邮箱已存在";
				}
			}
			if ("success".equals(msg)) {
				JSONObject obj = new JSONObject();
				obj.put("realname",realname);
				obj.put("username",username);
				obj.put("password",password);
				obj.put("email",email);
				accountService.saveAccount(obj);

				SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password));
				Object object = SecurityUtils.getSubject().getPrincipal();
				if (object != null) {
					accountObject = accountService.findByName(username);
					session.setAttribute("currentaccount", accountObject);
				}
			}
		} catch (CustomAuthenticationException exception) {
			logger.info("账户校验异常");
			msg = exception.getMessage();
		}
		return msg;
	}
}
